import axios from 'axios'
import { Message } from 'element-ui'
import store from '@/store'
import { getTimestamp, setTimestamp } from './auth'
import router from '@/router'

// 判断Token是否超时
function isToken() {
  const quantum = 60 * 2 * 60 * 1000
  return Date.now() - getTimestamp() > quantum
}

// create an axios instance
const service = axios.create({
  baseURL: process.env.VUE_APP_BASE_API, // url = base url + request url
  // withCredentials: true, // send cookies when cross-domain requests
  timeout: 5000 // request timeout
})

// request interceptor 请求拦截器
service.interceptors.request.use(confing => {
  // console.log(confing)
  if (store.getters.token) {
    // token超时处理
    if (isToken()) {
      store.dispatch('user/logout')
      router.push('/login')
      return Promise.reject(new Error('token 请求超时'))
    }
    // 在token没超时发送请求重新计算超时时间
    setTimestamp()

    confing.headers.Authorization = `Bearer ${store.getters.token}`
  }
  return confing
}, error => {
  return Promise.reject(error)
})

// response interceptor 响应拦截器
service.interceptors.response.use(res => {
  // 网络请求成功
  const { message, data, success } = res.data
  if (success) {
    return data
  } else {
    Message.error(message)
    return Promise.reject(new Error(message))
  }
}, err => {
  // 网络请求失败
  // console.dir(err)
  if (err.response && err.response.data && err.response.data.code === 10002) {
    store.dispatch('user/logout')
    router.push('/login')
  }
  Message.error(err.message)
  return Promise.reject(err)
})

export default service

